package com.gack.business.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gack.business.model.JobRank;
import com.gack.business.model.Message;
import com.gack.business.model.Position;
import com.gack.business.repository.ContactsRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.JobRankRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.PositionRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.vo.PositionVO;
import com.gack.helper.common.util.MapAsReturn;

@Service
@Transactional
public class PositionService implements PositionServiceInterface{

	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private PositionRepository positionRepository;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	@Autowired
	private ContactsRepository contactsRepository;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private JobRankRepository jobRankRepository;
	/**
	 * 查询某公司下所有职位
	 * @param enterpriseId 公司id
	 * @return status:error/success  msg:错误或成功信息  positionList:职位集合
	 */
	@Override
	public Map<String, Object> findAllPosition(String enterpriseId) {
		List<PositionVO> positionList = positionRepository.findVOByEnterpriseId(enterpriseId);
		return MapAsReturn.setStatusSuccess("positionList", positionList);
	}
	
	/**
	 * 新增某公司的职位   不可重名
	 * @param enterpriseId 公司id
	 * @param positionName 职位名称
	 * @param rankId 职级id
	 * @return status:error/success  msg:错误或成功消息(hasName)
	 */
	@Override
	public Map<String, Object> insertPosition(String enterpriseId, String positionName, String rankId) {
		//检查职级是否在该公司下
		if(null == jobRankRepository.findByEnterpriseIdAndId(enterpriseId, rankId)){
			return MapAsReturn.setStatusError("职级有误");
		}
		
		//检查是否重名
		if(positionRepository.countSameName(enterpriseId, positionName) > 0){
			return MapAsReturn.setStatusError("有重名情况,请修改后再试");
		}
	
		Position position = new Position();
		position.setEnterpriseId(enterpriseId);//设置公司id
		position.setJobrankId(rankId);//设置职级
		position.setName(positionName);//设置职位名称
		position.setStatus(1);//设置职位状态为"未删除"
		position.setUpdateTime(new Date());//设置update时间
		positionRepository.save(position);
		
		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	/**
	 * 修改职位    不可重名
	 * @param enterpriseId 公司id 
	 * @param positionId 职位id
	 * @param positionName 职位名称
	 * @param operatorId 操作者id
	 * @param rankId 职级id
	 * @return  status:error/success  msg:错误或成功消息(hasName)
	 */
	@Override
	public Map<String, Object> updatePosition(String enterpriseId, String positionId, String positionName, String operatorId, String rankId) {
		if(positionRepository.countByEnterpriseIdAndPositionId(enterpriseId, positionId) == 0){
			return MapAsReturn.setStatusError("该公司下无此职位");
		}
		
		JobRank jobRank = jobRankRepository.findByEnterpriseIdAndId(enterpriseId, rankId);
		if(null == jobRank){
			return MapAsReturn.setStatusError("非法操作");
		}
		
		//检查重名
		if(positionRepository.countSameNameExcludeMe(enterpriseId, positionId, positionName) > 0){
			return MapAsReturn.setStatusError("有重名情况,请修改后再试");
		}
		
		Position position = positionRepository.findOne(positionId);
		String oldPositionName = position.getName();
		position.setName(positionName);
		position.setJobrankId(rankId);
		position.setUpdateTime(new Date());
		positionRepository.save(position);
		
		//查询该公司下该职位的人员id
		List<String> userIds = userEnterpriseDepartmentPositionRepository.findUserIdByEnterpriseIdAndPositionId(enterpriseId, positionId);
		
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorId, enterpriseId);
		
		for(String t : userIds){
			String friendRemarks = contactsRepository.findFriendRemarks(operatorId, t);
			
			String text = "";
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				text = "管理员【" + friendRemarks + "】已将" + enterpriseName + "的" + oldPositionName + "改名为" + positionName + ",因此您在该公司的职位被更改为" + positionName;
			}else{
				text = "管理员【" + enterpriseRemarks + "】已将" + enterpriseName + "的" + oldPositionName + "改名为" + positionName + ",因此您在该公司的职位被更改为" + positionName;
			}
			
			Message message = new Message();
			//向公司的员工发送消息,告知管理权限的解除
			message.setUserid(t);//设置接受者id
			message.setMessage(text);//设置消息内容
			message.setCreatetime(new Date());//设置创建时间
			message.setTitle("系统消息");//设置标题
			message.setMesType(5);//设置消息类型为"系统消息"
			message.setState(2);//设置消息状态为"未处理"
			message.setCreateId(operatorId);//设置创建者id
			message.setSendWay(2);//设置发送方式为"站内信"
			message.setIsRead(0);//设置为"未读"
			messageRepository.save(message);
		}
		
		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	/**
	 * 批量删除某些职位,并将相应用户的职位置为null
	 * @param enterpriseId 公司id
	 * @param positionIds 职位id集合
	 * @param operatorId 操作者id
	 * @return
	 */
	public Map<String, Object> deletePositionByBatch(String enterpriseId, String[] positionIds, String operatorId) throws Exception{
		Map<String, Object> map = new HashMap<>();
		
		for(String t : positionIds){
			map = deletePosition(enterpriseId, t, operatorId);
			if(map.get("status").equals("error")){
				throw new RuntimeException("---msg:" + (String)map.get("msg"));
			}
		}
		
		return map;
	}
	
	/**
	 * 删除某职位,并将相应用户的职位置为null
	 * @param enterpriseId 公司id
	 * @param positionId 职位id
	 * @param operatorId 操作者id
	 * @return status:error/success  msg:错误或成功消息
	 */
	@Override
	public Map<String, Object> deletePosition(String enterpriseId, String positionId, String operatorId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		if(positionRepository.countByEnterpriseIdAndPositionId(enterpriseId, positionId) == 0){
			map.put("status", "error");
			map.put("msg", "该公司下无此职位");
			return map;
		}
		
		//查询该公司下该职位的人员id
		List<String> userIds = userEnterpriseDepartmentPositionRepository.findUserIdByEnterpriseIdAndPositionId(enterpriseId, positionId);
		
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String positionName = positionRepository.findNameById(positionId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorId, enterpriseId);
		
		for(String t : userIds){
			String friendRemarks = contactsRepository.findFriendRemarks(operatorId, t);
			
			String text = "";
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				text = "管理员【" + friendRemarks + "】已将" + enterpriseName + "的" + positionName + "删除,因此您在该公司的职位被取消";
			}else{
				text = "管理员【" + enterpriseRemarks + "】已将" + enterpriseName + "的" + positionName + "删除,因此您在该公司的职位被取消";
			}
			
			Message message = new Message();
			//向公司的员工发送消息,告知管理权限的解除
			message.setUserid(t);//设置接受者id
			message.setMessage(text);//设置消息内容
			message.setCreatetime(new Date());//设置创建时间
			message.setTitle("系统消息");//设置标题
			message.setMesType(5);//设置消息类型为"系统消息"
			message.setState(2);//设置消息状态为"未处理"
			message.setCreateId(operatorId);//设置创建者id
			message.setSendWay(2);//设置发送方式为"站内信"
			message.setIsRead(0);//设置为"未读"
			messageRepository.save(message);
		}
		
		//删除该职位
		Position position = positionRepository.findOne(positionId);
		if(position != null){
			position.setStatus(0);
			position.setDeleteTime(new Date());
			positionRepository.save(position);
		}
		
		//将相应人员的职位id置为空
		userEnterpriseDepartmentPositionRepository.setNullPositionIdByPositionId(positionId, new Date());
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
}
